package com.ww.juc.futureandcallable;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
public class JavaFutureDemo {
	
	private static Logger log = LoggerFactory.getLogger(GuavaFutureDemo.class);

    public static final int SLEEP_GAP = 500;

    public static String getCurThreadName() {
        return Thread.currentThread().getName();
    }

    static class HotWarterJob implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            try {
                log.info("洗好水壶");
                log.info("灌上凉水");
                log.info("放在火上");
                // 烧水中...
                Thread.sleep(SLEEP_GAP);
            } catch (InterruptedException e) {
                log.info("发生异常中断了");
                return false;
            }

            log.info("水已烧开");
            return true;
        }
    }

    static class WashJob implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            try {
                log.info("洗茶壶");
                log.info("洗茶杯");
                log.info("拿茶叶");
                // 洗水壶中
                Thread.sleep(SLEEP_GAP);
                throw new RuntimeException("手动抛异常了");
//                log.info("洗完了");
            } catch (InterruptedException e) {
                log.info("清洗工作中断了");
                return false;
            }
//            log.info("清洗工作已完成");
//            return true;
        }
    }

    public static void drinkTea(boolean waterOk, boolean cupOk) {
        if (waterOk && cupOk) {
            log.info("泡茶喝");
        } else if (!waterOk) {
            log.info("水还没烧好");
        } else if (!cupOk) {
            log.info("杯子还没洗了");
        }
    }

    public static void main(String[] args) {
        Callable<Boolean> hJob = new HotWarterJob();
        FutureTask<Boolean> hTask = new FutureTask<>(hJob);
        Thread hThread = new Thread(hTask, "** 烧水-Thread");
        Callable<Boolean> wJob = new WashJob();
        FutureTask<Boolean> wTask = new FutureTask<>(wJob);
        Thread wThread = new Thread(wTask, "$$ 清洗-thread");
        hThread.start();
        wThread.start();

        Thread.currentThread().setName("主线程");
        try {
            Boolean warterOk = hTask.get();
            Boolean cupOk = wTask.get();
            drinkTea(warterOk, cupOk);
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("运行结束了");
    }
}
